#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <netinet/in.h>//struct socket_in 结构
#include <sys/socket.h>//socket接口头文件
#include <arpa/inet.h>//字节序转换接口头文件

int main()
{
  //创建套接字
  int sockfd=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
  if(sockfd<0)
  {
    perror("socket error!");
    return -1;

  }

  //为套接字绑定地址信息
  
  struct sockaddr_in srv_addr;
  srv_addr.sin_family=AF_INET;//协议族
  srv_addr.sin_port=htons(9090);
  srv_addr.sin_addr.s_addr=inet_addr("192.168.227.143");
  //INADDR_ANY (0.0.0.0),及绑定所有网卡地址
  
  socklen_t len=sizeof(struct sockaddr_in);



  int ret=bind(sockfd,(struct sockaddr*)&srv_addr,len);
  if(ret<0)
  {
    perror("bind error!");
    close(sockfd);
    return -1;
  }


  //接收数据
  while(1)
  {
    char buf[1024]={0};
    struct sockaddr_in cli_addr;
    ret=recvfrom(sockfd,buf,1023,0,(struct sockaddr*)&cli_addr,&len);
    if(ret<0)
    {
      perror("recvfrom error!");
      close(sockfd);
      return -1;
    }

    printf("client %s %d:say %s\n",inet_ntoa(cli_addr.sin_addr),ntohs(cli_addr.sin_port),buf);

  //发送数据
  printf("server say:");
  fflush(stdout);

  char data[1024]={0};
  fgets(data,1023,stdin);
  ret =sendto(sockfd,data,strlen(data),0,(struct sockaddr*)&cli_addr  ,len);
  if(ret<0)
  {
    perror("sendto error!");
    close(sockfd);
    return -1;
  }

  }

  //关闭套接字
  close(sockfd);




  return 0;
}
